﻿#coding=utf-8

import wx
import wx.html
from product import *

class MyPrinter():   
    @classmethod
    def getHtmlPrinter(cls, parent):    
        htmlP = wx.html.HtmlEasyPrinting(u"销售单预览", parent)
       
        setupData = htmlP.GetPageSetupData()
        #print setupData.GetEnableMargins()
        #print setupData.GetMarginTopLeft()
        #print setupData.GetMarginBottomRight()
        
        # 想用下面的设置直接使用默认打印机的PaperSize，但总是(0,0)
        # printData = htmlP.GetPrintData()
        # print printData.GetPrinterName()
        # print dir(printData)
        
        # setupData.SetDefaultMinMargins(True)
        # setupData.SetDefaultInfo(True)
        # print setupData
        # print dir(setupData)
        # print setupData.GetDefaultMinMargins()
        # print setupData.GetDefaultInfo()
        
        setupData.SetMarginTopLeft((5,1))
        setupData.SetMarginBottomRight((1,1))
        #print setupData.GetMarginTopLeft()
        #print setupData.GetMarginBottomRight()
        
        #print setupData.GetPaperSize()
        setupData.SetPaperSize(CDataTableSale.getPaperSize())
        #print setupData.GetPaperSize()
        
        return htmlP
        
    def preview():
        htmlP.PreviewText(self.htmlText)
##        self.printData = wx.PrintData() 
##        self.printData.SetPaperId(wx.PAPER_LETTER) 
##        self.printData.SetPrintMode(wx.PRINT_MODE_PRINTER) 
##        data = wx.PrintDialogData(self.printData) 
##        printout = wx.html.HtmlPrintout('printout') 
##        printout2 = wx.html.HtmlPrintout('printout for printing')
##        printout.SetHtmlText(self.htmlText)
##        printout2.SetHtmlText(self.htmlText)
##        self.preview = wx.PrintPreview(printout, printout2, data)#第一步创建预览设备 
##        if not self.preview.Ok(): 
##            wx.MessageBox("error") 
##            return
##        self.preview.SetZoom(100) 
##        pfrm = wx.PreviewFrame(self.preview, parentWindow.GetParent(), "This is a print preview")#第二步创建框架 
##        pfrm.Initialize()#第三步初始化框架
##        pfrm.SetPosition(parentWindow.GetPosition())#设置默认的位置 
##        pfrm.SetSize(parentWindow.GetSize())#设置打印预览框的大小 
##        pfrm.Show(True) 
    

    @classmethod
    def getTitleHtml(cls):
        tblSale = CDataTableSale.getTableSale()
        header = tblSale.getValue(CDataTableSale.iTitle).replace(' ', '&nbsp;')        
        
        title = u'''<h3 align='center'>%s</h3>'''%header       
        
        return title
        
    @classmethod
    def getFooterHtml(cls, num=-1):
        tblSale = CDataTableSale.getTableSale()
        footer = tblSale.getValue(CDataTableSale.iFooter).replace(' ', '&nbsp;')
        footer = footer.split('\n')  
        
        if num == 0:
            return (u'', 0)
            
        if num > 0:
            num = min(num, len(footer))
        else:
            num = len(footer)
            
        htmlText = u'''<table  align='center' cellpadding='0' cellspacing='1' width='80%%'>'''
        for i in range(num):
            htmlText += u'''<tr><td align='left'>%s</td></tr> '''   %(footer[i])
        htmlText += u'''</table>'''
        
        return (htmlText, num)
    
    @classmethod
    def getDetailHtml(cls, strTemplate, detailList, iStart, num):
        html = u''
        
        if iStart >= len(detailList):
            return (html, 0)
        
        num = min(len(detailList[iStart:]), num)
        for idx,obj in enumerate(detailList[iStart:iStart+num]):        
            str = strTemplate
            str = str.replace(u'@index', u'%d'%(idx+1+iStart))
            str = str.replace(u'@proName', obj.getValue(obj.COL_PRONAME))
            str = str.replace(u'@unit', obj.getValue(obj.COL_UNIT))
            str = str.replace(u'@num', u'%g'%obj.getValue(obj.COL_NUM))
            str = str.replace(u'@price', u'%g'%obj.getValue(obj.COL_PRICE))
            str = str.replace(u'@total', u'%g'%obj.getValue(obj.COL_TOTAL))
            str = str.replace(u'@memo', obj.getValue(obj.COL_MEMO))
            str = str.replace(u'@proSpec', obj.getValue(obj.COL_PROSPEC))
    
            html += str
            
        return (html, num)
        
    @classmethod
    def printSaleOrder(cls, parent, saleId, printDebt=True, printFund=False):
        
        soObj = CDataSaleOrder.findObj(saleId)
        if (soObj is None):
            print '[Error %s]' %saleId
            return
        
        if not soObj.isPrinted():
            soObj.setPrinted()
            
        header = cls.getTitleHtml()
        footer,footer_cnt = cls.getFooterHtml()            
                              
        with open('./print_templates/sale.html', 'r') as f:
            template = f.read()
            template = template.decode('gbk')
        
        custId = soObj.getFieldVal('peerId')
        custObj = CDataCustomer.findObj(custId)
        
        # 填充订单信息
        template = template.replace(u'@cutomer', custObj.getValue(custObj.COL_NAME))        
        template = template.replace(u'@contact', u'电话：'+custObj.getValue(custObj.COL_LMPHONE))
        template = template.replace(u'@billid', saleId)
        template = template.replace(u'@delivery', soObj.getDlvyAddr())
        template = template.replace(u'@date', soObj.getValue(soObj.COL_BILLDATE).strftime('%Y-%m-%d'))
        #template = template.replace(u'@order_memo', soObj.getValue(soObj.COL_MEMO))         
        
        debt = None
        if printDebt:    
            debt = custObj.getDebt()
            amount = soObj.getValue(soObj.COL_TOTAL)
            #print (debt, amount)
            if abs(debt) < 0.01 or abs(debt-amount) < 0.01:
                debt = None
        
        if debt:                   
            template = template.replace(u'@balance', u'应付：%g元'%debt)
        else:
            template = template.replace(u'@balance', u'')
        
        # order_memo 放在最后与“合计”一起
        order_memo = soObj.getValue(soObj.COL_MEMO)
        if printFund:
            # 添加该客户未付订单信息
            fundStr = u''
            dataList = CDataSaleOrder.getBillAmount(custObj.getKeyVal())
            for id,total,paid,discount,unpaid in dataList:
                if unpaid > 0.0:
                    fundStr += u'%s-%s %g元, ' %(id[7:9], id[9:11], unpaid)
            if fundStr:
                order_memo = u'%s 【%s】' %(order_memo, fundStr[:-2])
        
        # 填充订单明细
        filter = "billId='%s'" %saleId
        detailList = CDataSaleDetail.fetch(filter, True)

        tag = template.find(u'@index')
        i_start = template.rfind(u'<tr', 0, tag)
        i_end = template.find(u'</tr>', tag) + len('</tr>')
        
        
        if CDataTableSale.isOmitHead() or len(detailList) < CDataTableSale.getNormalLineNum():          
            items = []
            
            for idx,obj in enumerate(detailList):
                str = template[i_start:i_end]
                str = str.replace(u'@index', u'%d'%(idx+1))
                str = str.replace(u'@proName', obj.getValue(obj.COL_PRONAME))
                str = str.replace(u'@unit', obj.getValue(obj.COL_UNIT))
                str = str.replace(u'@num', u'%g'%obj.getValue(obj.COL_NUM))
                str = str.replace(u'@price', u'%g'%obj.getValue(obj.COL_PRICE))
                str = str.replace(u'@total', u'%g'%obj.getValue(obj.COL_TOTAL))
                str = str.replace(u'@memo', obj.getValue(obj.COL_MEMO))
                str = str.replace(u'@proSpec', obj.getValue(obj.COL_PROSPEC))
                items.append(str)
                

            # 这里还需要想办法计算一下，如果最后一页只打印footer，那么就不要
            template = header + template[:i_start] + u' '.join(items) + template[i_end:] + footer            
            
        else:             
            # '统计行'、'合并行'
            extra_line = 0
            extra_start = 0
            extra_end = 0            
            tag = template.find('@sum_total')
            #print tag
            if tag > 0:
                extra_line += 1
                extra_start = template.rfind(u'<tr', 0, tag)
                extra_end = template.find(u'</tr>', tag) + len('</tr>')
                
            tag = template.find('@order_memo')
            #print tag
            if tag > 0 and order_memo:
                extra_line += 1
                extra_start = min (template.rfind(u'<tr', 0, tag), extra_start)
                extra_end = max (template.find(u'</tr>', tag) + len('</tr>'), extra_end)
            
            # 计算页数
            # 在二等分纸上，可以添加18行
            page_line = CDataTableSale.getMaxLineNum()
            #print page_line
            page_num = (len(detailList) + extra_line)/(page_line)
            item_num_lastpage = (len(detailList) + extra_line)%(page_line)
            if item_num_lastpage > 0:
                page_num += 1
                
                foot_num =  min(page_line-item_num_lastpage, footer_cnt)
            else:
                foot_num = 0
            
            page = u''
            for i in range(page_num):

                detail,num = cls.getDetailHtml(template[i_start:i_end], detailList, i*page_line, page_line)
                #print (detail,num)
                page += header + template[:i_start] + detail                
             
                if i == page_num -1:
                    # 最后一页了，把剩余行填充extra line 和footer
                    page += template[extra_start:extra_end] + u"</table>"
                    footer,cnt = cls.getFooterHtml(foot_num)
                    page += footer
                else:
                    page += u"</table>"
                
            template = page            
            
        num = sum([obj.getValue(obj.COL_NUM) for obj in detailList])    
        template = template.replace(u'@sum_num', u'%g'%num) 
        template = template.replace(u'@sum_total', u'%g'%soObj.getValue(soObj.COL_TOTAL)) 
        template = template.replace(u'@order_memo', order_memo)       
        #print template
        
        htmlP = cls.getHtmlPrinter(parent)
        if len(detailList) > CDataTableSale.getNormalLineNum(): 
            htmlP.SetHeader(u"<div align='right'><tr>第@PAGENUM@/@PAGESCNT@页</tr></div>")
        htmlP.PreviewText(template)
        
    @classmethod
    def __printSaleOrder(cls, parent, saleId, printDebt=True, printFund=False):
        #if saleId == '':
        #    return
            
        #soObj = CDataSaleOrder.getInstance({'id':saleId})
        soObj = CDataSaleOrder.findObj(saleId)
        if (soObj is None):
            print '[Error %s]' %saleId
            return
        
        if not soObj.isPrinted():
            soObj.setPrinted()
        
        #购货单位
        custId = soObj.getFieldVal('peerId')
        #custObj = CDataCustomer.getInstance({'id':custId})
        custObj = CDataCustomer.findObj(custId)
        #kh = custObj.getFieldVal('name')\
        #    + ' ' + custObj.getFieldVal('linkman')\
        #    + ' ' + custObj.getFieldVal('lm_phone') 
        #kh = custObj.getFieldVal('name')
        kh = custObj.getValue(custObj.COL_PRINTNAME)
        if (kh == ''):
            kh = custObj.getValue(custObj.COL_NAME)
    
        phone = ''
        if (CDataTableSale.includePhone()):
            phone = custObj.getValue(custObj.COL_LMPHONE)
        
        buyer = soObj.getValue(soObj.COL_BUYER)
        if (buyer != '' and buyer is not None and CDataTableSale.includeBuyer()):
                kh += ' (' + buyer + ')'
                
        #配送地址
        #dlvyId = soObj.getFieldVal('dlvyId')
        #if (dlvyId is None):
        #    dlvy = ''
        #else:
        #    dlvy = CDataDelivery.getFirstFieldVal({'id':dlvyId},'name')
        #dlvy = soObj.getFieldVal('dlvyAddr')
        dlvy = soObj.getDlvyAddr()
        
        #订单日期
        billDate = soObj.getFieldVal('billDate')
        
        #产品列表
        filter = "billId='%s'" %saleId
        proObjList = CDataSaleDetail.fetch(filter)
        proDetails = []
        cnt = 0
        amount = 0
        for i in range(len(proObjList)):
            row = []
            row.append(proObjList[i].getFieldVal('proName'))
            row.append(proObjList[i].getFieldVal('unit'))
            row.append(proObjList[i].getFieldVal('num'))
            row.append(proObjList[i].getFieldVal('price'))
            row.append(proObjList[i].getFieldVal('total'))
            row.append(proObjList[i].getFieldVal('memo'))
            cnt += row[2]
            amount += row[4]
            proDetails.append(row)
            
            # 以下代码书写方式不正确
            # proDetails.append[proObjList[i].getFieldVal('proName'), 
                                # proObjList[i].getFieldVal('unit'),
                                # proObjList[i].getFieldVal('num'),
                                # proObjList[i].getFieldVal('price'), 
                                # proObjList[i].getFieldVal('total')]
        
        if isinstance(billDate, unicode):
            date = billDate
        else:
            date = u'%d年%d月%d日' %(billDate.year, billDate.month, billDate.day)
        
        debt = None
        if (printDebt and CDataTableSale.includeDebt()):
            debt = custObj.getDebt()
            print (debt, amount)
            if abs(debt) < 0.01 or abs(debt-amount) < 0.01:
                debt = None
##            if (debt > 0.0):
##                date_debt = u'应付账款：' + str(debt) + u' 元'
            
        
        memo = soObj.getValue(soObj.COL_MEMO)
        if printFund:
            # 添加该客户未付订单信息
            fundStr = u''
            dataList = CDataSaleOrder.getBillAmount(custObj.getKeyVal())
            for id,total,paid,discount,unpaid in dataList:
                if unpaid > 0.0:
                    fundStr += u'%s-%s %g元, ' %(id[7:9], id[9:11], unpaid)
            if fundStr:
                memo = u'%s 【%s】' %(memo, fundStr[:-2])
                    
        #打印设置
        htmlP = cls.getHtmlPrinter(parent)
        htmlText = cls.makeSaleOrderHtml(saleId, kh, dlvy, date, debt, proDetails, cnt, amount, memo, phone)
        htmlP.SetHeader(u"<div align='right'><tr>第@PAGENUM@/@PAGESCNT@页</tr></div>")
        # footer = u'地址：南宁市五一路南四里8号(五一车管所对面)\n' 
        # footer += u'电话：0771-2412420   18978819291\n'
        # footer += u'本公司专业经营各类渔牧养殖、工业、农业、建筑、家居用筛网，铁钉铁线，聚乙烯醇，保温钉胶水等'
        # htmlP.SetFooter(footer)
        print htmlText
        htmlP.PreviewText(htmlText)
    
    @classmethod    
    def __makeSaleOrderHtml(cls, saleId, kh, dlvy, date, debt, proDetails, cnt, amount, memo='', phone=''):
        maxProLines = 10
        if (len(proDetails) > maxProLines):
            htmlText2 = cls.makeSaleOrderHtml(saleId, kh, dlvy, date, debt, proDetails[maxProLines:], cnt, amount)
            bLastPage = False
            curLines = maxProLines
        else:
            htmlText2 = ''
            bLastPage = True
            curLines = len(proDetails)
        
        tblSale = CDataTableSale.getTableSale()
        header = tblSale.getValue(CDataTableSale.iTitle).replace(' ', '&nbsp;')
        footer = tblSale.getValue(CDataTableSale.iFooter).replace(' ', '&nbsp;')
        footer = footer.split('\n')
        
        phoneStr = ''
        if (phone != ''):
            phoneStr = u'电话：%s' %phone
           
        debtStr = ''
        if debt is not None:
            debtStr = u'应付：%g元' %debt
        
        htmlText = u'''<h3 align='center'>%s</h3>
                    <table align='center' width='99%%'>
                    <tr>
                    <td align='left'>单位：%s</td>
                    <td align='left'>%s</td>
                    <td align='right'>单号：%s</td>
                    </tr>
                    <tr>
                    <td align='left'>配送：%s</td>
                    <td align='left'>%s</td>
                    <td align='right'>日期：%s</td>
                    </tr>
                    </table>''' %(header, kh, phoneStr, saleId, dlvy, debtStr, date)
        
        htmlText += u'''<table bgcolor='white' border='1px dashed' cellpadding='0' cellspacing='1' align='center' width='99%%'>
                    <tr>
                    <th width='5%'>序号</th>
                    <th width='35%'>品名</th>
                    <th width='10%'>单位</th>
                    <th width='10%'>数量</th>
                    <th width='10%'>单价</th>
                    <th width='10%'>小计</th>
                    <th width='10%'>备注</th>
                    </tr>
                '''
                
        bgColor = ['White', 'Silver'] 
        for i in range(curLines):
            price = '---' if proDetails[i][3]==0.0 else '%g' %proDetails[i][3]
            total = '---' if proDetails[i][4]==0.0 else '%g' %proDetails[i][4]
            htmlText += u'''<tr bgcolor='%s'>
                <td>%d</td>
                <td align='left'>&nbsp;&nbsp; %s</td>
                <td>%s</td>
                <td align='right'>%g &nbsp;&nbsp;</td>
                <td align='right'>%s &nbsp;&nbsp;</td>
                <td align='right'>%s &nbsp;&nbsp;</td>
                <td align='left'>%s</td>
                </tr>
                ''' %(bgColor[i%2], i+1, proDetails[i][0], 
                    proDetails[i][1],
                    proDetails[i][2],
                    price, total, proDetails[i][5])
        if (bLastPage):
            sCnt = '%g' %cnt
            sAmount = '%g' %amount
        else:
            sCnt = '---'
            sAmount = '---'
        
        htmlText += u'''<tr>
                    <td colspan='3'><b>合计</b></td>
                    <td align='right'>%s  &nbsp;&nbsp;</td>
                    <td align='right'>---  &nbsp;&nbsp;</td>
                    <td align='right'>%s  &nbsp;&nbsp;</td>
                    <td align='right'></td>
                    </tr>

                    <tr>
                    <td>备注</td>
                    <td colspan='6' align='left'>%s</td>
                    </tr>

                    </table>
                ''' %(sCnt, sAmount, memo)
                        
##        htmlText += u'''<table  align='center' width='80%%'>
##                <tr><td align='left'>地址：南宁市五一路南四里8号(五一车管所对面) &nbsp;&nbsp;&nbsp;&nbsp; 电话：0771-2412420 &nbsp;&nbsp; 18978819291</td></tr>
##                <tr><td align='left'>账号：邮政6210956110000142984 &nbsp;&nbsp; 农行6228450830043215314 &nbsp;&nbsp; 户名：吕文光</td></tr>                
##                <tr><td align='left'>本公司专业经营各类渔牧养殖、工业、农业、建筑筛网，铁钉铁线，聚乙烯醇，保温钉胶水等</td></tr> 
##                </table>
##            '''
        htmlText += u'''<table  align='center' width='80%%'>'''
        for str in footer:
            htmlText += u'''<tr><td align='left'>%s</td></tr> '''   %(str)
        htmlText += u'''</table>'''
        return htmlText + htmlText2
        
        
class MyPrinterSO(MyPrinter):
        
    def __init__(self, saleId=''):
        MyPrinter.__init__(self)
        
        if saleId == '':
            return
        
        self.soObj = CDataSaleOrder.getInstance({'id':saleId})
        if (self.soObj is None):
            print '[Error %s]' %saleId
            return
            
        custId = self.soObj.getFieldVal('peerId')
        self.custObj = CDataCustomer.getInstance({'id':custId})
        
        #dlvyId = self.soObj.getFieldVal('dlvyId')
        #self.dlvyObj = CDataDelivery.getInstance({'id':dlvyId})
        #dlvy = self.dlvyObj.getFieldVal('name')
        
        kh = self.custObj.getFieldVal('name')\
            + self.custObj.getFieldVal('linkman')\
            + self.custObj.getFieldVal('lm_phone')        
        
        dlvy = CDataDelivery.getFirstFieldVal({'id':self.soObj.getFieldVal('dlvyId')}, 'name')

        billdate = self.soObj.getFieldVal('billDate')
        
        self.htmlText = u'''<h3 align='center'>龙光筛网销售单</h3>
                    <table align='center' width='99%%'>
                    <tr>
                    <td align='left'>购货单位：%s</td>
                    <td align='right'>单号：%s</td>
                    </tr>
                    <tr>
                    <td align='left'>配送方式：%s</td>
                    <td align='right'>开单日期：%s</td>
                    </tr>
                    </table>''' %(kh, saleId, dlvy, billdate)
        
##        self.proList = []
        filter = "billId='%s'" %saleId
        proObjList = CDataSaleDetail.fetch(filter)
       
##        for proStr in proListStr:
##            pro = CDataSaleDetail.convertToObj(proStr)
##            self.proList.append(pro)
            
        self.htmlText += u'''<table bgcolor='white' border='10px dashed' cellpadding='0' cellspacing='1' align='center' width='99%%'>
                    <tr>
                    <th width='5%'>序号</th>
                    <th width='35%'>品名</th>
                    <th width='10%'>单位</th>
                    <th width='15%'>数量</th>
                    <th width='15%'>单价</th>
                    <th width='15%'>小计</th>
                    </tr>
                '''
        totalNum = 0        
        for i in range(len(proObjList)):
            self.htmlText += u'''<tr>
                <td>%d</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                </tr>
                ''' %(i+1, proObjList[i].getFieldVal('proName'), 
                    proObjList[i].getFieldVal('unit'),
                    proObjList[i].getFieldVal('num'),
                    proObjList[i].getFieldVal('price'),
                    proObjList[i].getFieldVal('total'))
            totalNum += proObjList[i].getFieldVal('num')
            
        # fk = u'''已付￥%d 未付￥%d 优惠￥%d''' %(self.soObj.getFieldVal('paid'),
                        # self.soObj.getFieldVal('unpaid'),
                        # self.soObj.getFieldVal('discount'))        
        fk = u'付款情况'
        self.htmlText += u'''<tr>
                    <td colspan='3'><b>合计</b></td>
                    <td>%d</td>
                    <td></td>
                    <td>%s</td>
                    </tr>
                    <tr>
                    <td>付款情况：</td>
                    <td colspan='5'>%s</td>
                    </tr>

                    <tr>
                    <td>备注</td>
                    <td colspan='5'>%s</td>
                    </tr>

                    </table>
                ''' %(totalNum, self.soObj.getFieldVal('total'), fk,
                        self.soObj.getFieldVal('memo'))
                        
        self.htmlText += u'''<table  align='center' width='80%%'>
                <tr><td align='left'>地址：南宁市五一路南四里8号(五一车管所对面)</td></tr>
                <tr><td align='left'>电话：0771-2412420 &nbsp;&nbsp;&nbsp;&nbsp; 18978819291</td></tr>
                
                </table>
            '''
       #     <tr><td align='left'>本公司主要批发经营：</td></tr>
  # <tr><td align='left'>&nbsp;&nbsp;&nbsp;&nbsp;常用筛网：焊网，钢板网，防蚊纱窗，网片，圆孔网，土工布(无纺布)</td></tr>
   ##            <tr><td align='left'>&nbsp;&nbsp;&nbsp;&nbsp;养殖网：塑料平网，鸡网，猪床网，鸽笼</td></tr>
     #           <tr><td align='left'>&nbsp;&nbsp;&nbsp;&nbsp;工地网系列：安全网，聚乙烯醇（速溶胶丝），胶水，保温钉</td></tr>
      #          <tr><td align='left'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;砂浆网，批灰网，网格布，收口网，钢筋网片</td></tr>
            
        